<template>
  <c-loading :loading="loading">
    <view class="container order-info">
      <view class="order-top block">
        <view class="status" :class="orderStatusColor(order)">{{ order.orderStatusName }}</view>
        <view class="desc">{{ getOrderDesc(order) }}</view>
      </view>
      <view class="address-wrap block top-line">
        <c-icon size="40" icon="location" />
        <view class="address-box">
          <view class="consignee">
            <text class="name">{{ order.formData.consignee }}</text>
            <text>{{ hideMobile(order.formData.consigneePhone) }}</text>
          </view>
          <view class="row2 address">{{ order.formData.region?.join(' ') }} {{ order.formData.address }}</view>
        </view>
        <!-- <c-icon icon="chevron-right"  /> -->
      </view>
      <view class="block">
        <order-item v-for="item in order.items" :key="item.id" v-bind="item">
          <template v-if="canAfterSales(item, order)">
            <c-button size="mini" @tap.stop="toAfterSalesInfo(item)" v-if="isAfterSales(item, order)">查看售后</c-button>
            <c-button size="mini" @tap.stop="toApplyAfterSales(item)" v-else type="warn" plain>申请售后</c-button>
          </template>
        </order-item>
      </view>

      <view class="block box">
        <view class="row">
          <view class="label">商品小计</view>
          <view class="value"><c-number precision-mini :precision="2" prefix="￥" :value="order.goodsAmount" /></view>
        </view>
        <view class="row">
          <view class="label">配送服务</view>
          <view class="value">
            <text class="marr">快递</text>
            <c-number precision-mini :precision="2" class="price" prefix="￥" v-if="order.freightFee" :value="order.freightFee" />
            <text v-else class="bold">包邮</text>
          </view>
        </view>
        <view class="row">
          <view class="label">优惠</view>
          <view class="value"><c-number precision-mini :precision="2" prefix="-￥" :value="order.discountAmount" /></view>
        </view>
        <view class="row" v-if="order.deductionAmount">
          <view class="label">会员减免</view>
          <view class="value"><c-number precision-mini :precision="2" class="price" prefix="-￥" :value="order.deductionAmount" /></view>
        </view>
        <view class="row">
          <view class="label">{{ order.paymentTime ? '实付' : '实付' }}</view>
          <view class="value">
            <c-number precision-mini :precision="2" class="price" prefix="￥" :value="order.paymentAmount" />
          </view>
        </view>
      </view>
      <view class="block box">
        <view class="row" @tap="copy(order.orderNo)">
          <view class="label">订单编号</view>
          <view class="grow"></view>
          <view class="value">{{ order.orderNo }}</view>
          <c-icon color="var(--color-primary)" icon="file-copy" />
        </view>
        <view class="row">
          <view class="label">下单时间</view>
          <view class="value">
            {{ order.createTime }}
          </view>
        </view>
        <view class="row" v-if="order.paymentTime">
          <view class="label">支付时间</view>
          <view class="value">
            {{ order.paymentTime }}
          </view>
        </view>
        <view class="row" v-if="order.deliveryTime">
          <view class="label">发货时间</view>
          <view class="value">
            {{ order.deliveryTime }}
          </view>
        </view>
        <view class="row" v-if="order.signTime">
          <view class="label">签收时间</view>
          <view class="value">
            {{ order.signTime }}
          </view>
        </view>
        <view class="row" v-if="order.closeTime">
          <view class="label">关单时间</view>
          <view class="value">
            {{ order.closeTime }}
          </view>
        </view>
        <view class="row">
          <view class="label">订单备注</view>
          <view class="value remark">
            {{ order.remark || '无备注' }}
          </view>
        </view>
      </view>
      <view class="fixed-footer flex al-center shadow" v-if="order.orderStatus == 0 || (order.deliveryTime && !order.closeTime) || order.orderStatus == 30">
        <c-number precision-mini :precision="2" v-if="order.orderStatus == 0" class="price" prefix="￥" :value="order.paymentAmount" />
        <view class="grow"></view>
        <c-button size="inline" v-if="order.orderStatus == 0" plain type="danger" @tap="toCancel(order)">取消订单</c-button>
        <c-button size="inline" v-if="order.orderStatus == 0" type="danger" @tap="toPay(order)">立即支付</c-button>
        <c-button size="inline" v-if="order.deliveryTime" type="primary" plain @tap.stop="lookDelivery(order)">查看物流</c-button>
        <c-button size="inline" v-if="order.orderStatus == 20" type="primary" @tap.stop="signFor(order)">确认收货</c-button>
        <c-button size="inline" v-if="order.orderStatus == 80 && !order.evaluateTime" type="primary" @tap.stop="toEvaluate(order)">去评价</c-button>
      </view>
      <view class="end"></view>
    </view>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CNumber, CIcon } from '@/components';
import OrderItem from './components/order-item.vue';
import { useRouter, useLoading, hideMobile, timeCountdown } from '@/hooks';
import api from '@/api';
import { reactive, ref } from 'vue';
import { View, Text } from '@tarojs/components';
import {
  setClipboardData,
  getAccountInfoSync,
  requestPayment,
  usePullDownRefresh,
  stopPullDownRefresh,
  useDidShow,
  useUnload,
  useDidHide,
  navigateToMiniProgram,
  showActionSheet
} from '@tarojs/taro';
import toast from '@/utils/toast';
import { APPID } from '@/utils/config';
const router = useRouter();
const order = ref({
  formData: {}
});
const now = ref(Date.now() / 1000);
let t = 0;
const { loading, restart } = useLoading(async options => {
  order.value = await api.order.info({
    orderNo: options.id
  });
});

const orderStatusColor = order => {
  switch (order.orderStatus) {
    case 0:
    case 20:
      return 'color-warn';
    case 100:
    case 101:
    case 102:
      return 'color-gray';
    default:
      return 'color-primary';
  }
};

useDidShow(() => {
  now.value = Date.now() / 1000;
  t = setInterval(() => {
    now.value = Date.now() / 1000;
  }, 1000);
});
useUnload(() => {
  t && clearInterval(t);
  t = 0;
});
useDidHide(() => {
  t && clearInterval(t);
  t = 0;
});
let isIn = false;

const startReload = async () => {
  if (isIn) {
    return;
  }
  isIn = true;
  for (let i = 0; i < 3; i++) {
    await restart();
    await Promise.sleep(5000);
    if (order.value.orderStatus != 0 && order.value.orderStatus != 10 && order.value.orderStatus != 20) break;
  }
  isIn = false;
};
const getOrderDesc = order => {
  switch (order.orderStatus) {
    case 0:
      if (order.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `还剩${timeCountdown(order.operationExpiredTimestamp, now.value)}自动取消`;
    case 10:
      return '订单已支付等待商家发货';
    case 12:
      return '商家已接单，正在备货中...';
    case 20:
      if (order.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `还剩${timeCountdown(order.operationExpiredTimestamp, now.value)}自动签收`;
    case 100:
    case 101:
    case 102:
    default:
      return '';
  }
};

const canAfterSales = (item, order) => {
  if (order.orderStatus >= 10 && order.orderStatus <= 80 && !order.closeTime) {
    return true;
  }
  return false;
};
const isAfterSales = (item, order) => {
  return order.orderAfterStatus == 1 && item.afterSaleQty > 0;
};
const toApplyAfterSales = item => {
  router
    .push('/pagesOrder/aftersales/apply', {
      ...order.value,
      ...item
    })
    .then(data => {
      restart();
    });
};
const toAfterSalesInfo = item => {
  router.push('/pagesOrder/aftersales/info?id=' + item.afterNo).then(data => {
    restart();
  });
};
const copy = e => {
  setClipboardData({
    data: e,
    success() {
      toast.success('订单号已复制');
    }
  });
};

usePullDownRefresh(async () => {
  await restart();
  stopPullDownRefresh();
});
const toCancel = order => {
  toast.confirm('确认关闭交易', '提示').then(async () => {
    await api.order.close({ id: order.orderNo }).toast('取消成功', true);
    restart();
  });
};

const toEvaluate = order => {
  router.push('/pagesBus/evaluate/publish?id=' + order.orderNo).then(() => {
    restart();
  });
};
const toPay = async order => {
  const packageV = await api.order.doPay({
    orderNo: order.orderNo,
    payChannel: 'WechatMini',
    partyAppId: APPID.value
  });
  requestPayment({
    ...packageV,
    success() {
      api.order.queryPay({ orderNo: order.orderNo }).then(r => {
        restart();
        router.callback({});
      });
    },
    fail(e) {
      // showComplete.value = true;
      // paySuccess.value = false;
    }
  });
};

const toDeliveryApp = expressNo => {
  navigateToMiniProgram({
    appId: 'wx6885acbedba59c14',
    path: 'pages/result/result?nu=' + expressNo,
    extraData: {
      nu: expressNo
    },
    envVersion: 'release',
    success(res) {
      // 打开成功
    }
  });
};
const lookDelivery = order => {
  if (order.logistics.length == 1) {
    toDeliveryApp(order.logistics[0].logisticsNo);
  } else {
    showActionSheet({
      itemList: order.logistics.map(a => a.logisticsNo),
      success(r) {
        toDeliveryApp(order.logistics[r.tapIndex].logisticsNo);
      }
    });
  }
};
const signFor = order => {
  toast.confirm('确认已收到货').then(data => {
    return api.order
      .signFor({ id: order.orderNo })
      .then(() => {
        restart();
        router.callback({});
      })
      .toast('签收成功');
  });
};
</script>
<style lang="scss">
.container.order-info {
  .order-top {
    padding: 10px 30px 30px;
    .status {
      font-size: 40px;
      font-weight: bold;
      margin-bottom: 16px;
    }
    .desc {
      font-size: 24px;
      color: var(--color-gray);
    }
  }

  .address-wrap {
    padding: 30px 30px 40px;
    display: flex;
    align-items: center;
    position: relative;
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      height: 10px;
      width: 100%;
      background: var(--repeating-linear);
    }
    .address-box {
      margin-left: 20px;
      flex-grow: 1;
      .consignee {
        margin-bottom: 10px;
        color: var(--color-default);
        .name {
          font-weight: bold;
          margin-right: 10px;
        }
      }
      .address {
        font-size: 26px;
        line-height: 1.6em;
      }
    }
    .placeholder {
      font-size: 24px;
      color: var(--color-gray);
    }
  }

  .fixed-footer {
    .price {
      color: var(--color-danger);
      font-size: 36px;
      font-weight: bold;
    }
  }
  .tag {
    display: inline-block;
    line-height: 2em;
    font-size: 20px;
    padding: 0 18px;
    box-shadow: 0 0 3px var(--color-primary) inset;
    margin-left: 10px;
    border-radius: 10px;
  }
  .box {
    padding: 10px 30px;
    .row {
      display: flex;
      margin: 40px 0;
      justify-content: space-between;
      align-items: center;
      line-height: 1;
      font-size: 26px;
      .label {
        flex-shrink: 0;
        width: 5em;
        color: var(--color-gray);
        margin-left: 10px;
      }
    }
    .price {
      color: var(--color-danger);
    }
    .remark {
      display: flex;
      color: var(--color-gray);
      align-items: center;
    }
    .marr {
      margin-right: 10px;
    }
  }
}
</style>
